package com.csx.micrometer.common.filter;

import cn.hutool.core.util.StrUtil;
import com.csx.micrometer.common.constant.SystemParamManagerConstant;
import com.csx.micrometer.common.constant.TagConstant;
import com.csx.micrometer.common.util.SystemParamManagerUtils;
import org.springframework.core.env.Environment;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2022/11/20 20:30
 */
public class CommonTagsPool {

    private static Environment environment;

    public static void setMicrometerCoordinateProperties(Environment environment) {
        CommonTagsPool.environment = environment;
    }

    /**
     * 优先从 Environment环境变量里面取值, 如果取不到则从 System 环境变量里面取值
     */
    private static final Map<String, String> commonTagsMap = new LinkedHashMap<String, String>() {
        {
            put(TagConstant.REGION, getRegion());
            put(TagConstant.ZONE_ID, getZoneId());
            put(TagConstant.UNIT_ID, getUnitId());
            put(TagConstant.SYSTEM_ID, getSystemId());
            put(TagConstant.ENV_ID, getEnvId());
            put(TagConstant.APPLICATION, getApplication());
        }
    };

    public static Map<String, String> getCommonTagsMap() {
        return commonTagsMap;
    }

    private static String getRegion() {
        if(StrUtil.isEmpty(environment.getProperty(SystemParamManagerConstant.REGION))) {
            return SystemParamManagerUtils.getRegion();
        }
        return environment.getProperty(SystemParamManagerConstant.REGION);
    }

    private static String getZoneId() {
        if(StrUtil.isEmpty(environment.getProperty(SystemParamManagerConstant.ZONE_ID))) {
            return SystemParamManagerUtils.getZoneId();
        }
        return environment.getProperty(SystemParamManagerConstant.ZONE_ID);
    }

    private static String getUnitId() {
        if(StrUtil.isEmpty(environment.getProperty(SystemParamManagerConstant.UNIT_ID))) {
            return SystemParamManagerUtils.getUnitId();
        }
        return environment.getProperty(SystemParamManagerConstant.UNIT_ID);
    }

    private static String getSystemId() {
        if(StrUtil.isEmpty(environment.getProperty(SystemParamManagerConstant.SYSTEM_ID))) {
            return SystemParamManagerUtils.getSystemId();
        }
        return environment.getProperty(SystemParamManagerConstant.SYSTEM_ID);
    }

    private static String getEnvId() {
        if(StrUtil.isEmpty(environment.getProperty(SystemParamManagerConstant.ENV_ID))) {
            return SystemParamManagerUtils.getEnvId();
        }
        return environment.getProperty(SystemParamManagerConstant.ENV_ID);
    }

    private static String getApplication() {
        if(StrUtil.isEmpty(environment.getProperty(SystemParamManagerConstant.APPLICATION))) {
            return SystemParamManagerUtils.getApplication();
        }
        return environment.getProperty(SystemParamManagerConstant.APPLICATION);
    }
}
